package com.quickcode.example.volatiles;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
public class VolatileExample1 {

    public static final ExecutorService EXECUTOR_SERVICE = Executors.newCachedThreadPool();

    private static  boolean flag = false;  // 不安全，主线程改变flag值后，后台线程并未结束（后台线程未同步主内存中的最新值）
//    private static volatile boolean flag = false;  //线程安全，每次读取flag都会从主内存中同步过来

    public static void main(String[] args) {

        CountDownLatch countDownLatchEnd = new CountDownLatch(1);

        EXECUTOR_SERVICE.execute(() -> {
            log.info("我开始执行");
            Object o = new Object();
            while (!flag) {
//                System.out.println(flag);  //不加volatile关键字也能安全退出，因为sout输出底层中有synchronized关键字，会同步变更flag的值
            }
            log.info("我结束了");
            countDownLatchEnd.countDown();
        });
        try {
            Thread.sleep(1000 * 2);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        flag = true;
        System.out.println("flag:" + flag);
        try {
            countDownLatchEnd.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("主程序结束");
    }


}